import { useUserStore } from "@/store/modules/user"
import type { EventReceive, Message } from "@/types/chat"
import io from "socket.io-client"
import { showFailToast, showLoadingToast } from "vant"
import { nextTick, reactive, ref } from "vue"

// 用户存储
const userStore = useUserStore()

// 定义消息列表
export const messageList = ref<Message[]>([])

// 定义请求参数
const query = ref<object>({})

// 参数地址：https://socket.io/zh-CN/docs/v4/client-initialization/
// 参数地址：https://socket.io/zh-CN/docs/v2/client-initialization/
// 定义连接参数
const options = reactive({
    transports: [
        // 指定传输方式，如WebSocket
        'websocket',
        // 'polling'
    ],

    // 是否自动连接
    autoConnect: true,

    // 是否自动重新连接
    reconnection: true,

    // 重新连接尝试次数
    reconnectionAttempts: 3,

    // 重新连接延迟时间（毫秒）
    reconnectionDelay: 1000,

    // 指定token,高版本用法
    // auth: {
    //     token: `Bearer ${userStore.profile?.token}`
    // },

    // 自定义查询参数
    query,
    // 其他可选参数...
    // path: '/socket.io',
})

// 设置请求参数
export const setQuery = (params: object) => {
    query.value = params
}

export const socket = ref()

// 加载提示框
export const loadingInstance = ref()

// 初始化socket.io
export const initSocketIO = (socketioSrvUrl: string) => {
    // socket.value = io(import.meta.env.VITE_SOCKET_IO_SERVER, options)
    socket.value = io(socketioSrvUrl, options)

    loadingInstance.value = showLoadingToast({
        message: '拼命加载中',
        // background: 'rgba(0, 0, 0, 0.8)'
    })

    // 监听连接事件
    socket.value.on('connect', function() {
        // showToast('连接成功')
        console.log('监听连接')
        console.log(socket.value)
        loadingInstance.value.close()
    })

    // 接收服务器默认消息事件
    socket.value.on('receiveDefultMessageList', async function({data}: {data: Message[]}) {
        loadingInstance.value.close()
        messageList.value.push(...data);
        console.log('receiveDefultMessageList =', data);

        // 始终显示新一条消息
        await nextTick()
        window.scrollTo(0, document.body.scrollHeight)
    })

    // 接收聊天消息事件
    socket.value.on('receiveChatMessage', async function({data}: {data: Message}) {
        console.log('data =', data);
        
        // 设置消息为已读
        data.is_read = 1
        socket.value.emit('readChatMessage', {id: data.id})

        loadingInstance.value.close()
        messageList.value.push(data);
        console.log('receiveChatMessage =', data);

        // 始终显示新一条消息
        await nextTick()
        window.scrollTo(0, document.body.scrollHeight)
    })

    // 接收广播消息事件
    socket.value.on('receive_broadcast', async function({data}: {data: Message}) {
        console.log('data =', data);

        loadingInstance.value.close()
        messageList.value.push(data);
        console.log('receive_broadcast =', data);

        // 始终显示新一条消息
        await nextTick()
        window.scrollTo(0, document.body.scrollHeight)
    })

    // 监听服务器心跳事件
    socket.value.on('pong', (latency: any) => {
        console.log('pong =', latency);
    });

    // 监听失败事件
    socket.value.on('fail', function(result: EventReceive) {
        showFailToast(result.msg)
        console.log('fail =', result)
        console.log('fail message ='+ result.msg)
    });

    // 监听错误事件
    socket.value.on('error', (error: any) => {
        console.log('error =', error);
    });

    // 监听连接错误事件
    socket.value.on('connect_error', (error: any) => {
        showFailToast('连接错误')
        console.log('connect_error =', error);
    });

    // 监听断开连接事件
    socket.value.on('disconnect', function() {
        showFailToast('连接已断开')
        console.log('disconnect');
        console.log(socket.value);
    })
}
